package fu.capstone.hanoicityguide.common.utility;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalFloat;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import fu.capstone.hanoicityguide.dataaccess.base.BaseDAOImpl;
import fu.capstone.hanoicityguide.dataaccess.webservice.WebServiceDAO;
import fu.capstone.hanoicityguide.dataaccess.webservice.WebServiceDAOImpl;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;
import android.widget.TextView;

public class CheckForUpdatingUtil extends AsyncTask<Void, String, Boolean> {
	// variable
	private SoapObject soapArray;
	private SoapPrimitive soapPrimitive;
	private Context mContext;
	private boolean checkUpdate;

	private ProgressDialog progressDialog;

	// constructor
	public CheckForUpdatingUtil(Context ctx) {
		this.mContext = ctx;
	}

	// init webservice connection
	public SoapPrimitive initWebServicePrimitive(String methodName)
			throws IOException, XmlPullParserException {
		SoapPrimitive soapPrimitive = null;
		// init request
		try {
			SoapObject request = new SoapObject(WebServiceDAO.NAMESPACE,
					methodName);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.dotNet = true;
			envelope.setOutputSoapObject(request);
			MarshalFloat marshal = new MarshalFloat();
			marshal.register(envelope);
			HttpTransportSE httpTransport = new HttpTransportSE(
					WebServiceDAO.URL);
			httpTransport.call(WebServiceDAO.NAMESPACE + methodName, envelope);
			soapPrimitive = (SoapPrimitive) envelope.getResponse();
		} catch (Exception e) {
			Log.v("Init Webservice Primitive : ", e.toString());
		}
		return soapPrimitive;
	}

	public boolean checkDBVersion() {
		boolean checkVersion = false;
		// get lastest version from DBVersionId table from Webservice
		int wsLastestVersion = Integer
				.parseInt(soapPrimitive.toString().trim());
		BaseDAOImpl dao = new BaseDAOImpl(mContext);
		if (wsLastestVersion > dao.getLastestDBVersionId()) {
			return true;
		} else {
			return false;
		}

	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		publishProgress("INIT");
		publishProgress("Checking...");
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		// TODO Auto-generated method stub
		InternetSetting internetSetting = new InternetSetting();
		if (internetSetting.getConnectivityStatus(mContext)) {
			try {
				soapPrimitive = initWebServicePrimitive(WebServiceDAO.METHOD_GET_LASTESTVERSIONID);
				checkUpdate = checkDBVersion();
				if (checkUpdate) {
					publishProgress("New version available !");
					SystemClock.sleep(1000);
					return checkUpdate;
				} else {
					publishProgress("Your data version is up to date !");
					SystemClock.sleep(2000);
					checkUpdate = false;
					return checkUpdate;
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				checkUpdate = false;
			}
			return checkUpdate;

		} else {
			publishProgress("NOINTERNET");
			SystemClock.sleep(2000);
			checkUpdate = false;
			return checkUpdate;
		}

	}

	@Override
	protected void onPostExecute(Boolean result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		if (checkUpdate) {
			Intent i = mContext.getPackageManager().getLaunchIntentForPackage(
					mContext.getPackageName());
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			mContext.startActivity(i);
			progressDialog.dismiss();
		} else {
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
		}

	}

	@Override
	protected void onProgressUpdate(String... values) {
		// TODO Auto-generated method stub
		if (values[0].equals("INIT")) {
			progressDialog = new ProgressDialog(mContext);
			progressDialog.setIndeterminate(false);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setCancelable(false);
			progressDialog.setTitle("Checking for update !");
			progressDialog.show();
		} else if (values[0].equals("Your data version is up to date !")) {
			progressDialog.setMessage(values[0]);
		} else if (values[0].equals("NOINTERNET")) {
			InternetSetting internetSetting = new InternetSetting(mContext);
			internetSetting.showSettingsAlert();
		} else {
			progressDialog.setMessage(values[0]);
		}

		super.onProgressUpdate(values);
	}

}
